
from django.core.exceptions import PermissionDenied
from django.http import Http404
from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework.views import set_rollback


from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import APIException

class MyBaseException(APIException):
    code = 10000 # 0 正常，非0异常; 前端需要知道错误码
    message = _('未知异常.') # 前端获取信息，友好提示

    @classmethod
    def get_message(cls):
        return {
            'code': cls.code,
            'message': cls.message
        }


# 内部异常转换成自定义异常，不暴露细节
exc_map = {
}
import traceback
def global_exception_handler(exc, context):
    """
    对原来的异常处理，改造。
    原因是默认的异常直接返回Response, 我们需要修改data，修改不方便，所以我们现在直接改函数。
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    print('@#'*30)
    print(traceback.format_exc())
    print(exc,type(exc))
    # 写日志,
    print('@#'*30)

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}


        set_rollback()

    if isinstance(exc, MyBaseException):
        err_msg = exc.get_message()
    else:
        err_msg = exc_map.get(exc.__class__.__name__,MyBaseException).get_message()
    return Response(err_msg,status=200) # 就算错误也返回200; 虽然返回错误码，但是返回200，jquery走成功回调； 成功回调判断错误码，来展示

